package com.corgi.test.java8.map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @title: MapTest
 * @description:
 * @author: dengmiao
 * @create: 2020-02-27 16:20
 **/
public class MapOrder {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws JsonProcessingException {
        Map metaMap = new LinkedHashMap<Integer, Object>(4){
            {
                put(1, "a");
                put(3, "b");
                put(6, "c");
                put(4, "d");
            }
        };
        Map sortByKey = sortByKey(metaMap);
        System.out.println(objectMapper.writeValueAsString(sortByKey));
    }

    public static <K extends Comparable<? super K>,
            V extends Comparable<? super V>> Map<K, V> sortByKey(Map<K, V> map) {
        // Map<K, V> result = new LinkedHashMap<>();
        return map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldVal, newVal) -> oldVal,
                        LinkedHashMap::new));
                //.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        // return result;
    }
}
